define(function(require, exports, module) {
//	//将该页面路径上的&&flag=true去掉，防止刷新该页面的时候有该参数
//	var url=location.href;
//	var index=url.indexOf("&");
//	//如果在地址栏能找到"&"，那么重新请求该页面
//	if(index!=-1){
//		location.href=url.substring(0,index);
//	}
	
	var $ = require('jquery');
	var List = require('../util/list');
	require('../util/getURL.js');
	require('jbox');
	require('spin/1.3/spin.js');
	require('artTemplate/artTemplate/2.0.1/template.js');
	require('jquery/jquery-form/1.0.0/jquery.form.js');
	require('jquery/jquery-json/2.4.0/jquery.json.js');
	require('jquery/jquery-timeago/1.3.0/jquery.timeago.js');
	require('jquery/jquery-validation/1.11.0/jquery.validate');
	require('../util/tinymce-page.js');
	
	var flot = require('flot/flotr2');

	
	exports.options = {
		listLink : '',
		listParams : '',
		pageLink : '',
		pageParams : ''
	};
	var uid='';
	var isAttention="";
	var pida = UrlParm.parm("id");
	if($g_user.login == 'true'){
		uid = ''+$g_user.id;
	}else{
		uid = '-1';
	}
	var commendTo = '';
	var status = '';
	var price='';
	var t = "1";
	var s="10";
	var buySum=$("#buyCount").val();
	var remaining=0;
	var caps=0;
	var intervalTime="";
	var intervalId1="";
	var userfund;
	var a;
	
	//时间戳转换成日期
	exports.getLocalTime=function(now){ 
		var now=new Date(now);
        var year=now.getFullYear();     
        var month=now.getMonth()+1;     
        var date=now.getDate();     
        var hour=now.getHours();     
        var minute=now.getMinutes();     
        var second=now.getSeconds();   
        var ds=year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
        return ds;
        }; 
        
	// 贡献排行
	var supportRank = new List();
	supportRank.options.template = "fund_statistics-template";
	supportRank.options.container = "#fund_statistics";
	supportRank.options.links = {"list":$CONFIG.base_url +'/api/project/statistic/topcontribution/supports'};
	supportRank.options.params = {"pid" : pida, "p": 1, "s" : 5};
	supportRank.load(function(){
		$("#fund_statistics .cont_date").each(function(){
			var s_d=parseInt($(this).text());
			var new_date=exports.getLocalTime(s_d);
				$(this).text(new_date);
		});
	});
	
	//查看原图函数
	exports.showOrigImg=function(){
		$("p img").off();
		$("p img").attr({style:"cursor: pointer",title:"点击查看原图"});
		$("p img").on("click",function(){	
			var ht=$(this).clone();
			$("#imgshow").click();
			var s=ht.attr("src");
			var imgurl;
			if(s.lastIndexOf("x")!="-1"){
				imgurl=s.substring(0,s.lastIndexOf("/"));
			}else{
				imgurl=s;
			}; 
			ht.attr({src:imgurl,style:"cursor:''",width:"900px",height:"800px"});
			$("#show").html(ht);
		});
	};
	
	//获取推荐的积善家列表
	var getAdl = new List();
	getAdl.options.template = "proRecommender-template";
	getAdl.options.container = "#proRecommender";
	getAdl.options.links = {"list":$CONFIG.base_url +'/api/project/recommender'};
	getAdl.options.params = {"pid" : pida};
	getAdl.load();
	//获取公告
	exports.getAd=function(){
		exports.options.projectAdLink =$CONFIG.base_url +'/api/project/ad/get';
		exports.options.projectAdParams={"pid" : pida};
		var adList=$.get(exports.options.projectAdLink,exports.options.projectAdParams);
		adList.done(function(data){
			var adListStr=template.render("getAd-template",data);
			$("#getAd").empty().append(adListStr);
			//查看原图
			exports.showOrigImg();
			$("#ad_time").text($.timeago($("#ad_time").text()));
		});
	};
	exports.getAd();
	// 分享排行
	var shareRank = new List();
	shareRank.options.template = "share_statistics-template";
	shareRank.options.container = "#share_statistics";
	shareRank.options.links = {"list":$CONFIG.base_url +'/api/project/statistic/topcontribution/shares'};
	shareRank.options.params = {"pid" : pida, "p": 1, "s" : 5};
	shareRank.load(function(){
		$("#share_statistics .cont_date").each(function(){
			var s_d=parseInt($(this).text());
			var new_date=exports.getLocalTime(s_d);
			$(this).text(new_date);
		});
	});
	// 判断用户
	if(uid!="-1"){
		exports.options.userlink = $CONFIG.base_url + "/api/user";
		exports.options.userParams = {
			"uid" : uid
		};
		var userInfor = $.get(exports.options.userlink, exports.options.userParams);
		userInfor.done(function(data) {
			$(".user_name").text(data.user.name);
			if (data.user.roles == "charitarian") {
				$("#recommendProject").css("display", "block");
			}
		});
	}
	//当前日期
	var dqDate = new Date();
	 var vYear = dqDate.getFullYear();
	 var vMon =dqDate.getMonth() + 1;
	 var vDay = dqDate.getDate();
	 if(vMon<10){
		 s_today = vYear + "-" +vMon + "-"+(vDay < 10 ?vDay +"  ": vDay);
	 }else{
		 s_today = vYear + "-" +vMon + "-"+(vDay < 10 ?vDay +" ": vDay);
	 }
	//获取统计方法
	exports.getData=function getData(api,cid){
		exports.options.commentlink = $CONFIG.base_url + api;
		exports.options.commentParams = {
			"pid" : pida
		};
		var commentInfor = $.get(exports.options.commentlink, exports.options.commentParams);
		commentInfor.done(function(data) {
			var nDate='';
			var d=[];
			var x=[];
			for(var i=0;i<data.length;i++){
				nDate=exports.getLocalTime(data[i].date);
				nDate=nDate.substring(0,10);
				point =[i , data[i].count ];
				xpoint=[i,nDate];
				d.push(point);
				x.push(xpoint);
				if(nDate==s_today){
					if(api=="/api/project/statistic/comments"){
						$(".new_incress_comment em").text(data[i].count);
					}else if(api=="/api/project/statistic/attentions"){
						$(".new_incress_attention em").text(data[i].count);
					}else if(api=="/api/project/statistic/shares"){
						$(".new_incress_share em").text(data[i].count);
					}
					else if(api=="/api/project/statistic/supports"){
						$(".new_incress_support em").text(data[i].count);
					}
				}
			}
			exports.flots(d,30,x,cid);
		});
	};
	
	$("#addProjectAd").validate({
		rules : {
			title : {
				required :true,		
			}
		},
	messages : {
		title : {
			required:function(){
				$.jBox.tip('亲~公告标题不能为空！');
			},
		}
	},
	});
	
	//添加公告
	$("#addProjectAd .opposition-ok").click(function(e){
		 e.preventDefault();
		$("#addProjectAd .ad_pid").val(pida);
		$("#content").val(tinyMCE.get('content').getContent());
		var json = form2js("addProjectAd", '.', true);
		$this=$("#addProjectAd");
		if(!$this.valid()){
			return;
		};
		if($("#content").val()==""){
			$.jBox.tip('亲~公告内容不能为空！');
			return;
		}
		if(tinyMCE.get('content').getContent().length>2000){
			$.jBox.tip("亲~公告内容超过2000字啦！");
			return;
		}
		var postData = $.toJSON(json);
		$.ajax({
			url : $CONFIG.base_url + "/api/project/ad/add",
			type : "POST",
			data : postData,
			contentType : "application/json",
			success : function() {
				$(".close").click();
				exports.getAd();
			},
			error : function() {
				$.jBox.tip("亲~出错了！请重新填写");
			}
		});
	});
	
	//获取关注统计数据
	exports.getData("/api/project/statistic/attentions","attentionTable");
	//获取分享统计数据
	exports.getData("/api/project/statistic/shares","shareTable");
	//获取评论统计数据
	exports.getData("/api/project/statistic/comments","commentsTable");
	//获取资助统计数据
	exports.getData("/api/project/statistic/supports","supportsTable");
	// 表格和柱状图
	exports.flots=function flots(data,days,x,cid){
		var attentionTable = document.getElementById(cid);//关注
		var horizontal = (horizontal ? true : false);
		data = [ {
			data : data,
		} ];
		var options = {
			colors : [ '#00A8F0', '#C0D800', '#CB4B4B','#4DA74D', '#9440ED' ],
			legend : {
				position : 'nw',
			},
			xaxis : {
				ticks:x,
				title:'日期',
				parseFloat : false,
				minorTickFreq : 4,
				autoscaleMargin : 0.5,
				tickFormatter : Flotr.defaultTickFormatter, // 刻度的格式化方式
				tickDecimals : 0,
				margin : true,
			},
			yaxis : {
				min : 0,
				max : 100,
				noTicks : 5,
			},
			bars : {
				show : true,
				horizontal : horizontal,
				shadowSize : 0,
				barWidth : 0.2
			},
			grid : {
				color : '#cccccc', // => 表格外边框和标题以及所有刻度的颜色
				tickColor : '#DDDDDD', // => 表格内部线条的颜色
				verticalLines : true, // => 表格内部是否显示垂直线条

			},
			mouse:{
                track: true,          //  为true时,当鼠标移动到每个折点时,会显示折点的坐标
                trackAll: true,       // 为true时,当鼠标在线条上移动时,显示所在点的坐标
                position: 'se',        // 鼠标事件显示数据的位置 (default south-east)
                sensibility: 2,        // 值越小,鼠标事件越精确
         }
		};
		$('a[data-toggle="tab"]').on('shown', function() {
			Flotr.draw(attentionTable, data, options);
		});
	};
	
	// 定时器
	exports.time = function time() {
		t = t - 1;
		if (t < 0) {
			clearInterval(time);
			return false;
		}
		if (t == 0) {
			clearInterval(time);
			$(".letter_send_error").hide();
			$(".letter_send_seccuss").hide();
		}
	};
	// 定时器
	exports.auto_jump = function auto_jump() {
		secs = $(".showbox").first().text()-1;
		intervalTime=secs;
		$(".showbox").text(secs);
		if (secs < 0) {
			return false;
		}
		if (secs == 0) {
			clearInterval(time);
			 location.reload() ;
			exports.productsList();
		} else {

		}
	};
	
	//关闭jbox后继续执行定时
	exports.changeLocation = function changeLocation(){
		if(intervalTime==""){
			intervalTime=5;
		}
		intervalTime--;
		if (intervalTime < 0) {
			return false;
		}
		if (intervalTime == 0) {
			clearInterval(intervalId1);
			location.reload() ;
			exports.productsList();
		}
	};
	// 添加回复框
	exports.addChart = function addChart(uid, fid, commendTo) {
		$(this)	.parent().parent().after(
						"<tr><td colspan='4'><div id='chart_diag' class='chart_diag'><form id='lerterForm' method=post'><input type='hidden' name='userId' value='"
								+ uid
								+ "'/><input type='hidden' name='superComment.id' value='"
								+ commendTo
								+ "'/><input type='hidden' name='project.id' value='"
								+ pida
								+ "'/><input type='hidden' name='commentTo' value='"
								+ fid
								+ "'/><textarea rows='' cols='' name='content' maxlength='100' style='height:80px;'></textarea><br><button class='send_leter color_theme' style='float:left;'>发送</button></form></div></td></tr>");
	};

	// 商品信息
	exports.productsList = function productsList() {

		var product = new List();
		product.options.template = "productsList-template";
		product.options.container = "#productsList";
		product.options.links = {
			"list" : $CONFIG.base_url + '/api/project/product/list'
		};
		product.options.params = {
			"pid" : pida
		};
		product.load();
	};

	//加载 评论
	exports.comment = function comment(con,callback) {
		var showCom = new List();
		showCom.options.template = con+"-template";
		showCom.options.container = "#"+con;
		showCom.options.links = {
			"list" : $CONFIG.base_url + '/api/comment/project/list'
		};
		showCom.options.params = {
			"id" : pida,
			"p" : 1,
			"s" : s
		};
		showCom.load(function(){
			if(typeof(callback) == "function"){
				callback();
			}
		});
		
	};
	exports.format=function(e){
		$("#"+e+" .send_time").each(function(){
			var t=parseInt($(this).text());
			t=$.timeago(exports.getLocalTime(t));
			$(this).text(t);
		});
	};
	exports.comment("discussAll",function(){
		exports.format("tab-part1");
	});
	exports.comment("projectCommentList",function(){
		exports.format("tab-part5");
	});
	// 最新资助
	var newSupport = new List();
	newSupport.options.template = "tab-part6-template";
	newSupport.options.container = "#tab-part6";
	newSupport.options.links = {
		"list" : $CONFIG.base_url + '/api/project/support/list'
	};
	newSupport.options.params = {
		"pid" : pida,
		"p" : 1,
		"s" : 10
	};
	newSupport.load();

	// 回复评论
	$("#discussAll").on('click', '.returnMessage', function() {
		if($("#chart_diag").length==0){
			commendTo = $(this).prev().val();
			var fid = $(this).attr("data");
			$("#chart_diag").remove();
			commentTO=fid.substring(fid.indexOf(',')+1,fid.indexOf('}'));
			fid=fid.substring(fid.indexOf(',')+1,fid.indexOf('}'));
			exports.addChart.call(this, uid, fid, commentTO);
			$(".send_leter").click(function(e) {
				e.preventDefault();
				exports.submitForm(lerterForm, '/api/comment');
			});
		}else{
			$("#chart_diag").parent().parent().remove();
		}
		
	});
	$("#projectCommentList").on('click', '.returnMessage', function() {
		if($("#chart_diag").length==0){
			commendTo = $(this).prev().val();
			var data = $(this).attr("data");
			$("#chart_diag").remove();
			var index=data.indexOf(",");
			commentTo=data.substring(index+1,data.indexOf("}"));
			fid=commentTo;
			exports.addChart.call(this, uid, fid, commentTo);
			$(".send_leter").click(function(e) {
				e.preventDefault();
				exports.submitForm(lerterForm, '/api/comment');
			});
		}else{
			$("#chart_diag").parent().parent().remove();
		};
	});	
	// 发起新评论
	$("#startNewComment .raise-submit").click(function() {
		$(".pid").val(pida);
		$(".uid").val(uid);
		if(uid=="-1"){
			window.location.href=$CONFIG.base_url +"/login";
		}else{
			exports.submitForm(startNewComment, "/api/comment");
			$("#textarea-text1").val("");
		}
		
	});
	$("#startNewComment2 .raise-submit").click(function(e) {
		e.preventDefault();
		$(".pid").val(pida);
		$(".uid").val(uid);
		exports.submitForm(startNewComment2, "/api/comment");
		$("#textarea-text2").val("");
	});
	
	//删除评论
	exports.delComment=function(e){
		var postData={"cid":e,"uid":uid};
		$.jBox.tip("正在处理，请稍候...","loading");
		var posting = $.post($CONFIG.base_url + "/api/comment/del", postData);
		posting.done(function(data) {
			if(data.msg == 'true'){
				$.jBox.closeTip();
				$.jBox.tip("删除成功！");
				exports.comment("discussAll");
				exports.comment("projectCommentList");
			}else{
				$.jBox.closeTip();
				$.jBox.tip("对不起您没有权限删除该评论！");
			}
			
		}).fail(function() {
			$.jBox.closeTip();
			$.jBox.tip("删除失败！");
		});
	};
	$('#discussAll').on("click",".del_to_list",function(){
		var delId=$(this).attr('data');
		var submit = function (v, h, f) {
		    if (v == 'ok')
		    	exports.delComment(delId);
		    else if (v == 'cancel')
		    return true; //close
		};
		$.jBox.confirm("<span style='text-align:center;width:100%;display:block;color: #834313;'>您确定要删除？</span>", "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
	});
	$('#projectCommentList').on("click",".del_to_list",function(){
		var delId=$(this).attr('data');
		var submit = function (v, h, f) {
		    if (v == 'ok')
		    	exports.delComment(delId);
		    else if (v == 'cancel')
		    return true; //close
		};
		$.jBox.confirm("<span style='text-align:center;width:100%;display:block;color: #834313;'>您确定要删除？</span>", "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
	});
	// 关注服务
	exports.attention=function(callback){
		if($g_user.login!="true"){
			var submit = function (v, h, f) {
				if (v == 'ok')
					window.location.href=$CONFIG.base_url +"/login";
				else if (v == 'cancel')
					return true; //close
			};
			$.jBox.confirm("您还没有登录，是否登录？", "友情提示", submit);
			return false;
		}
		postData={"project":{"id":pida},"userId":uid};
		postData = $.toJSON(postData);
		$.ajax({
			url : $CONFIG.base_url
					+ "/api/project/attention",
			type : "POST",
			data : postData,
			contentType : "application/json",
			success : function(data) {
				if(typeof(callback) == "function"){
					callback();
				}
			},
			error : function() {
				jBox.tip('网络错误！');
			}
		});
	};
	$(".attention-project").click(function(){
		var getting=$.get($CONFIG.base_url+"/api/project",{"pid":pida,"uid":uid});
		getting.done(function(data){
			isAttention=data.project.isAttention;
			if(isAttention=="0"){
				exports.attention(function(){
					$('.attention-project-img').addClass("focus");
					jBox.tip('关注成功', '提示');
				});
			}else if(isAttention=="1"){
				exports.attention(function(){
					$('.attention-project-img').removeClass("focus");
					jBox.tip('取消关注成功', '提示');
				});
			}else{
				return;
			}
		});
		
	});
	
	var secs = '1';
	exports.hidde = function hidde() {
		secs = secs - 1;
		if (secs < 0) {
			return false;
		}
		if (secs == 0) {
			clearInterval(time);
			$(".letter_send_seccuss,.letter_send_error").hide();
		}
	};
	// 分享服务
	$("#shareTo").click(function() {
		$(".share").show();
		$(".bdsharebuttonbox a").click(function(){
			$(".share").hide(500);
		});
	});
	$('.close_share').click(function(){
		$(".share").hide();
	});
	$(".share .bdsharebuttonbox a").click(function(){
		var da=new Date().getTime();
		var share=new Object();
		var pid=new Object();
		pid["id"]=pida;
		share["project"]=pid;
		share["userId"]=uid;
		share["platform"]="3";
		share["shareLink"]=$CONFIG.base_url+ "/project/detail" + "?id="+ pida + "&uid=" +uid+ "&date=" + da;
		var postData = $.toJSON(share);
		$.ajax({
			url : $CONFIG.base_url + "/api/project/share",
			type : "POST",
			data : postData,
			// dataType : "json",
			contentType : "application/json",
			success : function() {
				$.jBox.tip("分享成功！");
			},
			error : function() {
				$.jBox.tip("分享失败，请重试！");
			}
		});
	});
	// 积善家推荐服务
	$("#recommend-project").click(function() {
		if(!$("#recommend-project i").hasClass('recommend_focus')){
			var submit = function (v, h, f) {
			    if (v == 'ok'){
					var postData={"project":{"id":pida},"user":{"id":uid}};
					postData = $.toJSON(postData);
					$.ajax({
						url : $CONFIG.base_url + "/api/project/recommend",
						type : "POST",
						data : postData,
						contentType : "application/json",
						success : function(data) {
								if(data.msg=="Recommend Success"){
									$('.support-project-img').addClass("recommend_focus");
									jBox.tip('推荐成功', '提示');
								}else{
									jBox.tip('推荐失败', '提示');
								}
						},
						error : function() {
							jBox.tip('推荐失败', '提示');
						}
					});
			    }else if (v == 'cancel'){
			    	jBox.tip('取消推荐', 'info');
			    }
			    return true; //close
			};
			$.jBox.confirm("确定推荐此服务吗？", "提示", submit);
		}else{
			jBox.tip('您已经推荐了此服务', '提示');
		}
	});	
	//购买数量注册事件函数
	exports.checkBuyNum=function(o){  //CTR+V事件处理 
        $("#"+o).val($("#"+o).val().replace(/\D|^0/g,''));  
		buySum=$("#"+o).val();
		if($("#"+o).val().trim()==""){
			$("#"+o).val(1);
		};
		$("#"+o).val(parseInt($("#"+o).val()));
		buySum=$("#"+o).val();
		$("#payCount").text(parseInt(buySum)*parseInt(price));
		exports.checkzfb();
	};
	
	//购买数量keyup事件
	exports.checkBuyNumKeyup=function(o){  //CTR+V事件处理 
        $("#"+o).val($("#"+o).val().replace(/\D|^0/g,''));  
		buySum=$("#"+o).val();		
		if($("#"+o).val().trim()==""){
			return;
		};
		$("#"+o).val(parseInt($("#"+o).val()));
		buySum=$("#"+o).val();		
		$("#payCount").text(parseInt(buySum)*parseInt(price));
		exports.checkzfb();
	};	
	//验证购买数量
	exports.checkBuy=function(){		
		$("#buyCount").keyup(function(){exports.checkBuyNumKeyup("buyCount");});
		$("#buyCount").bind("paste",function(){exports.checkBuyNum("buyCount");});
		$("#buyCount").blur(function(){exports.checkBuyNum("buyCount");});
	};
	
	exports.checkBuy();
	
	$("#buyCount").keyup(function(){
		buySum=$(this).val();
		$("#payCount").text(buySum*price);
		exports.checkzfb();
	}
	);
	exports.checkzfb = function(){
		if($("#use-zhye").attr("checked") == "checked"){
			var paysum = parseInt($("#payCount").text()) - userfund;
			if(parseInt(paysum) <= 0) {
				$("#zhifubao").text("0");
				$("#paybyzfb").hide();
			}else{
				$("#paybyzfb").show();
				$("#zhifubao").text(paysum);
			}
		}else{
			$("#paybyzfb").show();
			$("#zhifubao").text($("#payCount").text());
		}
	};
	// 购买（支持）服务
	$("#productsList").on("click",".sup-btn",function() {
		$(".giftsend").hide();
		if(status!="5"){
			$.jBox.tip("该服务的状态不是进行中，不能购买服务!");
			return false;
		}
		$(".back_to_top").click();
		if(uid=="-1"){
			var submit = function (v, h, f) {
			    if (v == 'ok')
			    	window.location.href=$CONFIG.base_url +"/login";
			    else if (v == 'cancel')
			    return true; //close
			};
			$.jBox.confirm("您还没有登录，是否登录？", "友情提示", submit);
		}else{
			$("#tab-part7").hide();
			$("#tab-part8").show();
			price = $(this).prev().children().text().substring(1);
			$("#payCount").text(price);
			$("#zhifubao").text($("#payCount").text());
			$("#use-zhye").change(function(){
				exports.checkzfb();
			});
			
			a = $(this).attr("data");
			$("#tab-part8 .buy").click(function() {
				$("#buy").css("display",'none');
				$.post($CONFIG.base_url +"/api/user/check_password?uid="+uid+"&oldPassword="+$(".zfb_password").val(),function(data){
					if(data=="true"){
						if($("#zhifubao").text() != '0'){
							var postData = {"user":{"id":uid},"amount":$("#zhifubao").text()};
							postData = $.toJSON(postData);
							$.ajax({
								url : $CONFIG.base_url+ "/api/fund_detail/web/deposit",
								type : "POST",
								data : postData,
								contentType : "application/json",
								success : function(data) {
									$.jBox.info('正在转到支付页面...', '提示');
									$("#deposit").append(data.sHtmlText);
								},
								error : function() {
								}
							});
						}else{
							exports.buy(a);
						}
						
					}else{
						$("#buy").css("display",'block');
						$(".zfb_password").val("");
						$.jBox.tip("密码错误,请重新输入！");
					}
				});
			});
		}
	});
	//购买
	exports.buy = function(a){
		var did = "product" + a;
		var fundCode = $("#" + did + " .fundCode").val();
		var postData={"user":{"id":uid},"project":{"id":pida},"fundCode":fundCode,"product":{"id":a},"productAmount":buySum};
		postData = $.toJSON(postData);
		$.ajax({
			url : $CONFIG.base_url+ "/api/project/support/add",
			type : "POST",
			data : postData,
			//dataType : "json",
			contentType : "application/json",
			success : function(data) {
				$.jBox.closeTip();
				$.jBox.info('<tr><td class="error_notice"><span class="show_success"></span>购买成功！<span class="showbox">5</span>秒后自动为您转跳到主页</td></tr>',"提示",{closed:function(){
					clearInterval(time);
					location.reload();
				}});
				time = setInterval(exports.auto_jump,1000);
			},
			error : function(data) {
				$("#buy").css("display",'block');
				var error= data.responseJSON.error;
				switch (error) {
				case "Lack of Funds!":
					$(".buy_show").empty().append('<tr><td class="error_notice"><span class="show_error"></span>您的账户余额不足，请先充值。</td></tr>');
					$('#tab-part8 .buy').val("立即充值");
					$('#tab-part8 .buy').click(function() {
						window.location.href = $CONFIG.base_url+ "/fund";
					});
					break;
				case "Remaining deficiencies":
					$(".buy_show").empty().append('<tr><td class="error_notice"><span class="show_error"></span>服务已售罄！<span class="showbox">5</span>秒后自动为您转跳到服务主页</td></tr>');
					time = setInterval(exports.auto_jump,1000);
					break;
				default:
					$(".buy_show").empty().append("<tr><td class='error_notice'><span class='show_error'></span>亲~你已超过该服务的购买限额！<span class='showbox'>5</span>秒后自动为您转跳到服务主页或<a href=''>点此返回</a>服务主页</td></tr>");
					$(".error_notice a").click(function() {location.reload();});
					time = setInterval(exports.auto_jump,1000);
					break;
				};
			}
		});
	}

	// 请客送礼服务
	exports.present = function(a,phone){
		var did = "product" + a;
		var fundCode = $("#" + did + " .fundCode").val();
		var postData={"user.id":uid,"project.id":pida,"fundCode":fundCode,"product.id":a,"productAmount":buySum,"phone":phone};
		$.post($CONFIG.base_url + "/api/project/support/present/send", postData).done(function(data) {
			$.jBox.closeTip();
			$.jBox.info('<tr><td class="error_notice"><span class="show_success"></span>送礼成功！<span class="showbox">5</span>秒后自动为您转跳到服务主页</td></tr>',"提示",{closed:function(){
				clearInterval(time);
				location.reload();								
			}});
			time = setInterval(exports.auto_jump,1000);
		}).fail(function(data){
			$("#buy").css("display",'block');
			var error= data.responseJSON.error;
			switch (error) {
			case "Lack of Funds!":
				$(".buy_show").empty().append('<tr><td class="error_notice"><span class="show_error"></span>您的账户余额不足，请先充值。</td></tr>');
				$('#tab-part8 .buy').val("立即充值");
				$('#tab-part8 .buy').click(function() {
					window.location.href = $CONFIG.base_url+ "/fund";
				});
				break;
			/*case "Remaining deficiencies":
				$(".buy_show").empty().append('<tr><td class="error_notice"><span class="show_error"></span>商品已售罄！<span class="showbox">5</span>秒后自动为您转跳到服务主页</td></tr>');
				time = setInterval(exports.auto_jump,1000);
				break;*/
			default:
				$(".buy_show").empty().append("<tr><td class='error_notice'><span class='show_error'></span>亲~你已超过该服务的购买限额！<span class='showbox'>5</span>秒后自动为您转跳到服务主页或<a href=''>点此返回</a>服务主页</td></tr>");
				$(".error_notice a").click(function() {location.reload();});
				time = setInterval(exports.auto_jump,1000);
				break;
			};
		});
	}
	
	
	
	$("#productsList").on("click",".gvgift-btn",function() {
		$(".bsend").css("display","block");
		$(".bbuy").hide();
		if(status!=5){
			$.jBox.tip("该服务的状态不是进行中，不能购买服务!");
			return false;
		}
		/*remaining=parseInt($("#remaining"+$(this).attr("data")).val());
		caps=parseInt($("#caps"+$(this).attr("data")).val());
		$(".limitbuy").text(caps);
		if(remaining==0){
			$.jBox.tip("该商品剩余0个，不能再购买了!");
			return;
		}*/
		$(".back_to_top").click();
		if(uid=="-1"){
			var submit = function (v, h, f) {
			    if (v == 'ok')
			    	window.location.href=$CONFIG.base_url +"/login";
			    else if (v == 'cancel')
			    return true; //close
			};
			$.jBox.confirm("您还没有登录，是否登录？", "友情提示", submit);
		}else{
			$("#tab-part7").hide();
			$("#tab-part8").show();
			price=$(this).siblings().find(".price").text().substring(1);
			$("#payCount").text(price);
			var a = $(this).attr("data");
			$("#zhifubao").text($("#payCount").text());
			$("#use-zhye").change(function(){
				exports.checkzfb();
			})
			$("#tab-part8 .buy").click(function() {
			var loginName=$(".loginN").attr("data");
			if($("#sePhone").val()==loginName){
					$.jBox.tip("亲~不能送给自己哦！");
					return;
				}
				$("#buy").css("display",'none');
				$.post($CONFIG.base_url +"/api/user/check_password?uid="+uid+"&oldPassword="+$(".zfb_password").val(),function(data){
					if(data=="true"){
							
							$(".bsend").css("display","none");
							 var regexp=/^((\(\d{3}\))|(\d{3}\-))?(1[3578]\d{9})$/;//验证手机
							 if(!((regexp.test($("#sePhone").val())))){
									$.jBox.tip("亲～电话号码格式不正确");
									$(".bsend").show();
									return;
								};
							var phone=$("#sePhone").val();
                            if(phone!=$("#againPhone").val()){
                            	$.jBox.tip("两次输入的手机号不一致！");
                            	$(".bsend").show();
                            	return;
                            };
                            if($("#zhifubao").text() != '0'){
    							var postData = {"user":{"id":uid},"amount":$("#zhifubao").text()};
    							postData = $.toJSON(postData);
    							$.ajax({
    								url : $CONFIG.base_url+ "/api/fund_detail/web/deposit",
    								type : "POST",
    								data : postData,
    								contentType : "application/json",
    								success : function(data) {
    									$("#deposit").append(data.sHtmlText);
    								},
    								error : function() {
    								}
    							});
    						}else{
    							 exports.present(a,phone);
    						}
                           
					}else{
						$(".zf_password").val("");
						$.jBox.tip("密码错误,请重新输入！");
					}
				});
			
			});
		}
		
		
	});
	exports.submitForm = function submitForm(e, v) {
		if($g_user.login=="false"){
			$.jBox.tip("亲~你还没有登录呢");
			setTimeout(window.location.href=$CONFIG.base_url +"/login",1000); 
		}else if($g_user.login=="true"){
			var json = form2js(e, '.', true);
			var postData = $.toJSON(json);
			$.ajax({
				url : $CONFIG.base_url + v,
				type : "POST",
				data : postData,
				contentType : "application/json",
				success : function(data) {
					if(data.msg=="comment_success"){
						
						$.jBox.tip("评论成功！");
						exports.comment("discussAll",function(e){
							exports.format("tab-part1");
						});
						exports.comment("projectCommentList",function(e){
							exports.format("tab-part5");
						});
					}else if(data.msg=="content_is_null"){
						$.jBox.tip("评论失败，请写入评论内容！");
					}
				},
				error : function() {
					$.jBox.tip("评论失败，请重试！");
				}
			});
		}
	};
	//验证送礼手机号

	//去掉字符串是首尾空格
	exports.checkTrim=function(cha){
		$(cha).val().replace(/(^\s+)|(\s+$)/g,"").replace(/\s/g,"");
	};
	
	//获取反馈
	exports.getfeedback=function(by){
	exports.options.feedbackLink = $CONFIG.base_url
			+"/api/project/"+by+"/list";
	exports.options.feedbackParams = {
				"pid" : pida
		};
	var feedbackList = $.get(exports.options.feedbackLink,
				exports.options.feedbackParams);
	feedbackList.done(function(data) {
			$("#"+by+"_fb_infor").empty();
			var fbList=new List();
			if(by=="schedule"){
				fbList=data.schedule;
			}else if(by=="budget"){
				fbList=data.budget;
			};
			for(var i=0;i<fbList.length;i++){
				var item=fbList[i].stage+" "+($.trim(fbList[i].feedback)==null||$.trim(fbList[i].feedback)==""?"暂无反馈":fbList[i].feedback)+ "<br/>";
				$("#"+by+"stage").append("<option>"+fbList[i].stage+"</option>");
				$("#"+by+"_fb_infor").append(item);
			};
			exports.showOrigImg();
		});
	};
	exports.getfeedback("schedule");
	exports.getfeedback("budget");
	
	//获取反对数
	exports.getUnsupportCount=function(){
		exports.options.getUnsupportcountLink=$CONFIG.base_url
			+ "/api/project/unsupport/getcount";
		var uid=$g_user.id;
		exports.options.getUnsupportcountParams={"pid":pida,"uid":uid};
		var getUnsupportcount=$.get(exports.options.getUnsupportcountLink,
				exports.options.getUnsupportcountParams);
		getUnsupportcount.done(function(data){
			$(".unsupportcount").empty().append(data.unSupportCount);
			if(uid!=null){
				$("#input-approve-upSupport").val(data.approveUnsupport);
			}
		});
	};
	//添加反对
	exports.addUnsupport=function(){
		exports.options.addUnsupportLink=$CONFIG.base_url+"/api/project/unsupport/add";
		var unsupport=new Object();
		var projectId=new Object();
		projectId["id"]=pida;
		unsupport["project"]=projectId;
		unsupport["userId"]=$g_user.id;
		var postData=$.toJSON(unsupport);
		if($("#input-approve-upSupport").val()=="false"){
			$.jBox.tip("没有购买该服务的记录，反对无效。请先购买服务！");
			return;
		}
		$.ajax({
				url : exports.options.addUnsupportLink,
				type : "POST",
				data : postData,
//				dataType : "json",
				contentType : "application/json",
				success : function(data) {
					if(data.msg=="success"){
						$.jBox.tip("反对成功！");
						exports.getUnsupportCount();
					}else{
						$.jBox.tip("只能反对一次！");
					}
				},
				error:function(data){
					$.jBox.tip("反对无效!");
				}			
		});
	};

	//添加反馈
	exports.addFeedback=function(by){
		exports.options.addFeedbackLink=$CONFIG.base_url+"/api/project/"+by+"/feedback/add";
		var projectId=new Object();
		var feedback=new Object();
		projectId["id"]=pida;
		feedback["project"]=projectId;
		feedback["stage"]=$("#"+by+"stage").val();
		feedback["feedback"]=$("#"+by+"_fb_Content").val();
		var postData=$.toJSON(feedback);
		$.ajax({
				url : exports.options.addFeedbackLink,
				type : "POST",
				data : postData,
				contentType : "application/json",
				success : function(data) {
					$("#"+by+"_fb_Modal").modal('hide');
					exports.getfeedback(by);
				},
				error:function(data){					
				}			
		});
	};
	//反对
	exports.unsupport=function(){	
		exports.getUnsupportCount();
		$(".fb_btn").click(function(){
			if($g_user.login == "false"){
				var submit = function (v, h, f) {
				    if (v == 'ok')
				    	window.location.href=$CONFIG.base_url +"/login";
				    else if (v == 'cancel')
				    return true; //close
				};
				$.jBox.confirm("您还没有登录，是否登录？", "友情提示", submit);
			}else{
				exports.addUnsupport();				
			};
		});
	};
	//反馈
	exports.feedback=function(by){		
		$("#"+by+"_fb_btn").empty().append("添加反馈");
		if($("#"+by+"stage").val()!=null){			
			$("#"+by+"_fb_btn").attr({href:"#"+by+"_fb_Modal"});
			$("#"+by+"_fb_save").click(function(){
				if($("#"+by+"_fb_Content").val()==null||$.trim($("#"+by+"_fb_Content").val())==""){
					$("#"+by+"_fb_Content").val("");
					$("#"+by+"_fb_Content").attr({placeholder:"反馈内容不能为空！"});
				}else{
					$("#"+by+"_fb_Content").attr({placeholder:"填写反馈内容"});
					exports.addFeedback(by);
				};			
			});
		}else{
			$("#"+by+"_fb_btn").click(function(){
				$("#"+by+"_fb_infor").empty().append('<small><div class="check-img"></div><span class="error">没有可以添加反馈的计划！</span></small>');
			});
		};
		
	};
	//反馈初始化
//	exports.initfb=function(){		
//		exports.feedback("schedule");
//		exports.feedback("budget");
//	};
	exports.loadSchduleFeedBack=function(){
		var scheduleFeedlList = new List();
		scheduleFeedlList.options.template = "schduleFeedBackTable-template";
		scheduleFeedlList.options.container = "#schduleFeedBackTable";
		scheduleFeedlList.options.links = {
			"list" : $CONFIG.base_url + "/api/project/schedule/list"
		};
		scheduleFeedlList.options.params = {
			"pid" : pida
		};
		scheduleFeedlList.load(function(){			
			exports.showOrigImg();
		});
	};
	
	exports.loadBudgetFeedBack=function(){
		var budgetFeedBackList = new List();
		budgetFeedBackList.options.template = "budgetFeedBackTable-template";
		budgetFeedBackList.options.container = "#budgetFeedBackTable";
		budgetFeedBackList.options.links = {
			"list" : $CONFIG.base_url + "/api/project/budget/list"
		};
		budgetFeedBackList.options.params = {
			"pid" : pida
		};
		budgetFeedBackList.load(function(){			
			exports.showOrigImg();
		});
	};
	exports.loadBudgetFeedBack();
	exports.loadSchduleFeedBack();
	//判断用户是否为服务发起人
	exports.feedbackInit=function(){
		exports.options.feedbackInitLink=$CONFIG.base_url
				+"/api/project";
		exports.options.feedbackInitParams={
				"pid":pida
		};
		var project=$.get(exports.options.feedbackInitLink
				,exports.options.feedbackInitParams);
		project.done(function(data){	
			isAttention=data.project.isAttention;
			if(data.project.institution.user.id==uid){
				//exports.initfb();
				$("#schduleFeedBackTable").after('<a id="schedule_fb_btn" role="button" class="opposition-against btn-r fb_btn" data-toggle="modal">添加反馈</a>');
				$("#budgetFeedBackTable").after('<a id="budget_fb_btn" role="button" class="opposition-against btn-r fb_btn" data-toggle="modal">添加反馈</a>');
				$("#schedule_fb_btn").click(function(){
					if(uid=="-1"){
						var submit = function (v, h, f) {
						    if (v == 'ok')
						    	window.location.href=$CONFIG.base_url +"/login";
						    else if (v == 'cancel')
						    return true; //close
						};
						$.jBox.confirm("您还没有登录，是否登录？", "友情提示", submit);
					}else{
						$("#schedule_fb_Modal").modal();
					}
				});
				$("#budget_fb_btn").click(function(){
					$("#budget_fb_Modal").modal();
				});
			}else{
				$(".fb_btn").empty().append("反对(<span class='unsupportcount'></span>人)");
				$("#schduleFeedBackTable").after('<a role="button" class="opposition-against btn-r fb_btn fb_btn" data-toggle="modal">反对<span class="unsupportcount"></span>人</a>');
				$("#budgetFeedBackTable").after('<a role="button" class="opposition-against btn-r fb_btn fb_btn" data-toggle="modal">反对<span class="unsupportcount"></span>人</a>');
				exports.unsupport();
			}
		});
	};
	
	
	exports.feedbackInit();
	//添加执行计划反馈
	$("#schedule_fb_save").click(function(){
		if($g_user.login == 'true'){
			uid = ''+$g_user.id;
		}else{
			uid = '-1';
		}
		if(uid=="-1"){
			var submit = function (v, h, f) {
			    if (v == 'ok')
			    	window.location.href=$CONFIG.base_url +"/login";
			    else if (v == 'cancel')
			    return true; //close
			};
			$.jBox.confirm("您还没有登录，是否登录？", "友情提示", submit);
		}else{
			$("#spid").val(pida);
			ed = tinyMCE.get('schedule_fb_Content');
			if(ed.getContent()==""){
				$.jBox.tip("亲~反馈内容不能为空哦!");
				return;
			}if(ed.getContent().length>2000){
				$.jBox.tip("亲~反馈内容超过2000字啦！");
				return;
			}
		    $("#schedule_fb_Content").val(ed.getContent());
			var json = form2js("scheduleFeedBack", '.', true);
			var postData = $.toJSON(json);
			$.ajax({
				url : $CONFIG.base_url + "/api/project/schedule/feedback/add",
				type : "POST",
				data : postData,
				contentType : "application/json",
				success : function() {
					$.jBox.tip("添加反馈成功！");
					$("#schedule_fb_Modal .close").click();
					exports.loadSchduleFeedBack();
					
				},
				error : function() {
					$.jBox.tip("添加反馈失败！");
				}
			});
		}
	});
	//添加预算反馈
	$("#budget_fb_save").click(function(){
		$("#bpid").val(pida);
		ed = tinyMCE.get('budget_fb_Content');
		if(ed.getContent()==""){
			$.jBox.tip("亲~反馈内容不能为空哦!");
			return;
		}
	    $("#budget_fb_Content").val(ed.getContent());
		var json = form2js("budgetFeedBack", '.', true);
		var postData = $.toJSON(json);
		$.ajax({
			url : $CONFIG.base_url + "/api/project/budget/feedback/add",
			type : "POST",
			data : postData,
			contentType : "application/json",
			success : function() {
				$.jBox.tip("添加反馈成功！");
				$("#budget_fb_Modal .close").click();
				exports.loadBudgetFeedBack();
			},
			error : function() {
				$.jBox.tip("添加反馈失败！");
			}
		});
	});
	//加载执行计划信息
	exports.loadSchdele=function(){		
		var schedulelList = new List();
		schedulelList.options.template = "scheduleList-template";
		schedulelList.options.container = "#scheduleList";
		schedulelList.options.links = {
			"list" : $CONFIG.base_url + "/api/project/schedule/list"
		};
		schedulelList.options.params = {
			"pid" : pida
		};
		schedulelList.load();
	};
	exports.loadSchdele();
	
	exports.options.projectCoverLink = $CONFIG.base_url
		+ "/api/project";
	exports.options.projectCoverPageParams = {
	"pid" : pida,
	"uid" : uid
	};
	var activityBack=$.get(exports.options.projectCoverLink,
			exports.options.projectCoverPageParams);
	activityBack.done(function(data){
		if(data.project.contect == '1'){
			var url = $CONFIG.base_url + '/api/configure/get';
			$.get(url).done(function(info){
				data.project.userRealName = info.username;
				data.project.userPhone = info.phone;
				data.project.mail = info.mail;
				data.project.userQQ = info.qq;
				var selectKind2 = template.render(
				'introduceProject-template', data);
			$('#introduceProject').empty().append(selectKind2);
			});
		}else{
		var selectKind2 = template.render(
				'introduceProject-template', data);
			$('#introduceProject').empty().append(selectKind2);
		}
	});
	
	//数字过大转换为“xx万”的形式
	exports.turn = function(){
		$("span[id=attentioncount]").each(function(){
			var val = $.trim($(this).text());
			if(val >= 1000000){
				val = val/10000;
				val = Math.round(val)
				$(this).empty().append("<b>"+val+"万</b>")
			}
			else if(val >= 100000){
				val = val/1000;
				val = Math.round(val);
				val = val/10;
				$(this).empty().append("<b>"+val+"万</b>")
			}
			else if(val >= 10000){
				val = val/100;
				val = Math.round(val);
				val = val/100;
				$(this).empty().append("<b>"+val+"万</b>")
			}else{
				$(this).empty().append("<b>"+val+"</b>")
			}
		});
		$("span[id=fundcurrent]").each(function(){
			var val = $.trim($(this).text());
			if(val >= 1000000){
				val = val/10000;
				val = Math.round(val)
				$(this).empty().append("<b>"+val+"万</b>")
			}
			else if(val >= 100000){
				val = val/1000;
				val = Math.round(val);
				val = val/10;
				$(this).empty().append("<b>"+val+"万</b>")
			}
			else if(val >= 10000){
				val = val/100;
				val = Math.round(val);
				val = val/100;
				$(this).empty().append("<b>"+val+"万</b>")
			}else{
				$(this).empty().append("<b>"+val+"</b>")
			}
		});
		$("span[id=productamount]").each(function(){
			var val = $.trim($(this).text());
			if(val >= 1000000){
				val = val/10000;
				val = Math.round(val)
				$(this).empty().append("<b>"+val+"万</b>")
			}
			else if(val >= 100000){
				val = val/1000;
				val = Math.round(val);
				val = val/10;
				$(this).empty().append("<b>"+val+"万</b>")
			}
			else if(val >= 10000){
				val = val/100;
				val = Math.round(val);
				val = val/100;
				$(this).empty().append("<b>"+val+"万</b>")
			}else{
				$(this).empty().append("<b>"+val+"</b>")
			}
		})
	}
	
	$(document).ready(function(data) {
						// 账户余额
						if($g_user.login == 'true'){
							$.get( $CONFIG.base_url + "/api/user",{"uid" : $g_user.id }).done(function(data){
								userfund = data.user.fund;
								$(".zhye").text(userfund);
							});
						}
						exports.productsList();
						//今日单笔最高
						exports.options.topRankLink = $CONFIG.base_url+ "/api/project/statistic/"+pida+"/topest";
						var topRankList = $.get(exports.options.topRankLink);
						topRankList.done(function(data) {
							$("#todayFound em").text(data.count);
						});
						// 服务详情
						exports.options.projectCoverLink = $CONFIG.base_url
								+ "/api/project";
						exports.options.projectCoverPageParams = {
							"pid" : pida,
							"uid" : uid
						};
						var goodsList = $.get(exports.options.projectCoverLink,
								exports.options.projectCoverPageParams);
						goodsList.done(function(data) {
							if(data.project.status<=1){
								$("#startNewComment2,#startNewComment,#schedule_fb_btn,#addAd").hide();
							}
							var start_pro_user_id=data.project.institution.user.id;
							if(start_pro_user_id!=uid){
								$("#tab-part5 #addAd").hide();
							}
							$("#commentCount em").text(data.project.commentCount);
							$("#attemtionCount em").text(data.project.attentionCount);
							$("#fundCount em").text(data.project.fundTarget);
							$("#getFound em").text(data.project.fundCurrent);
							$("#shareCount em").text(data.project.shareCount);
							$("#pre-time").text(data.project.createdDate);
							$("#pre-name").text(data.project.name);
							$("#insti-name").text(data.project.institution.name);
							$("#project-title-top").show();
							
							var isAttention = data.project.isAttention;
							var isRecommended=data.project.isRecommended;
							if (isAttention == 1) {
								$('.attention-project-img').addClass("focus");
							}
							if (isRecommended == 1) {
								$('.support-project-img').addClass("recommend_focus");
							}
							pid = data.project.id;
							status = data.project.status;
							var selectKind = template.render(
									'projectCover-template', data);
							$('#projectCover').empty().append(selectKind);

							var selectKind2 = template.render(
									'tabzfbTitle-template', data);
							$('#tabzfbTitle').empty().append(selectKind2);
							var selectKind2 = template.render(
									'projectInfor-template', data);
							$('#projectInfor').empty().append(selectKind2);

							var selectKind2 = template.render(
									'preShow-template', data);
							$('#preShow').empty().append(selectKind2);
							$('#preShow2').empty().append(selectKind2);
							exports.turn();

							var fundTarget = data.project.fundTarget;
							var fundCurrent = data.project.fundCurrent;
							var persent = fundCurrent / fundTarget;
							persent = Math.round(persent * 100 * 100) / 100;
							$("#projectInforBar div").css("width",
									persent + "%");
							$("#projectInforBar span").text(persent + "%");
							$("#projectInforBar div").css("width",
									persent + "%");
							$("#preShow .projectpledged").css("width",
									persent + "%");
						});

						
						
						// 费用预算信息
						exports.options.budgetLink = $CONFIG.base_url
								+ "/api/project/budget/list";
						exports.options.budgetParams = {
							"pid" : pida
						};
						var budgetList = $.get(exports.options.budgetLink,
								exports.options.budgetParams);
						budgetList.done(function(data) {
							var selectKind = template.render(
									'budgetList-template', data);
							$('#budgetList').empty().append(selectKind);

						});

						// 发起服务机构
						exports.options.projectStartOrgLink = $CONFIG.base_url
								+ "/api/project";
						exports.options.projectStartOrgParams = {
							"pid" : pida
						};
						var projectStartOrgList = $.get(
								exports.options.projectStartOrgLink,
								exports.options.projectStartOrgParams);
						projectStartOrgList.done(function(data) {
							var selectKind = template.render(
									'projectStartOrg-template', data);
							$('#projectStartOrg').empty().append(selectKind);
							
							//关于支付里获取的结束时间及目标金额在这里可以得到，所以写在这里
							var aboutPay=template.render('about-pay-template',data);
							$("#about-pay").empty().append(aboutPay);
						});
						
						$(".message_time>span").click(function() {
							if ($("#chart_diag").length) {
								$("#chart_diag").remove();
								$(this).addChart();
							} else {
								$("#chart_diag").remove();
								$(this).addChart();
							}
						});						
						//查看原图
						exports.showOrigImg();
					});
});
